package StudyCode.summary.myfile;

import java.io.*;
import java.nio.ByteBuffer;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class DiffFile {
	public static void main(String[] args) throws IOException {
		File file1 = new File("E:\\迅雷下载\\test1.txt");
		File file2 = new File("E:\\迅雷下载\\test1.txt");
		System.out.println(file1 + " 等于 " + file2 + " 吗？ " + diff(file1, file2));
	}

	private static boolean diff(File f1, File f2) throws IOException {
		if (f1 != null && !f1.exists())
			f1 = null;

		if (f2 != null && !f2.exists())
			f2 = null;

		if (f1 == f2 || f1 != null && f1.equals(f2))
			return true;

		if (f1 == null)
			return f2.length() != 0;

		if (f2 == null)
			return f1.length() != 0;

		long len = f1.length();

		if (len != f2.length())
			return true;

		DataInputStream s1 = new DataInputStream(new BufferedInputStream(
				new FileInputStream(f1)));
		DataInputStream s2 = new DataInputStream(new BufferedInputStream(
				new FileInputStream(f2)));

		long p = 0;

		for (; p < len - 7; p += 8) {
			if (s1.readLong() != s2.readLong())
				return true;
		}

		for (; p < len; p++) {
			if (s1.read() != s2.read())
				return true;
		}

		s1.close();
		s2.close();
		return false;
	}

	public static boolean diff(File f1, ByteBuffer b2) throws IOException {
		if (f1 != null && !f1.exists())
			f1 = null;

		if (b2 != null)
			b2 = b2.slice();

		if (f1 == null)
			return b2 != null && b2.remaining() != 0;

		if (b2 == null)
			return f1 != null && f1.length() != 0;

		if (f1.length() != b2.remaining())
			return true;

		DataInputStream s1 = new DataInputStream(new BufferedInputStream(
				new FileInputStream(f1)));
		final int len = b2.capacity();
		int p = 0;

		for (; p < len - 7; p += 8) {
			if (s1.readLong() != b2.getLong())
				return true;
		}

		for (; p < len; p++) {
			if (s1.read() != (b2.get() & 0xFF))
				return true;
		}

		s1.close();
		return false;
	}

	public static boolean diff(ByteBuffer b1, ByteBuffer b2)
			throws IOException {
		if (b1 == b2 || b1 != null && b1.equals(b2))
			return false;

		if (b1 == null)
			return b2 != null && b2.remaining() != 0;

		if (b2 == null)
			return b1 != null && b1.remaining() != 0;

		b1 = b1.slice();
		b2 = b2.slice();

		int len = b1.capacity();
		if (len != b2.capacity())
			return true;

		int p = 0;

		for (; p < len - 7; p += 8)
			if (b1.getLong() != b2.getLong())
				return true;

		for (; p < len; p++)
			if (b1.get() != b2.get())
				return true;

		return false;
	}
}
